def str_to_hex_array(s, is_32bit=False):
    """
    将字符串转换为10进制整数数组
    - is_32bit=True: 4个16进制字符一组（32bit）
    - is_32bit=False: 2个16进制字符一组（8bit，小端序）
    """
    if s.startswith('0x'):
        s = s[2:]
    step = 8 if is_32bit else 2
    if len(s) % step != 0:
        raise ValueError(f"输入字符串长度必须为{step}的倍数（不含0x前缀）")
    
    dec_array = []
    hex_str_list = []
    # 小端序处理：从右向左切分
    for i in range(len(s)-step, -1, -step):
        hex_str = s[i:i+step]
        dec_val = int(hex_str, 16)
        dec_array.append(dec_val)
        hex_str_list.append(f"0x{hex_str}")
    return dec_array, hex_str_list

def split_into_groups(arr, group_size=8):
    """将数组拆分为指定大小的子数组（每组8个元素）"""
    groups = []
    for i in range(0, len(arr), group_size):
        group = arr[i:i+group_size]
        if len(group) < group_size:
            group += [0] * (group_size - len(group))
        groups.append(group)
    return groups

def transpose_groups(groups):
    """对vs2分组进行转置（按列取元素）"""
    while len(groups) < 8:
        groups.append([0]*8)
    transposed = []
    for i in range(8):
        new_group = [groups[j][i] for j in range(8)]
        transposed.append(new_group)
    return transposed

def matrix_dot_product(mat1, mat2):
    """矩阵点乘：vs1的第i行 与 vs2转置后的第j行 点乘，结果为result[i][j]"""
    result = []
    print("矩阵点乘计算过程（行与行对应点乘）：")
    for i in range(8):  # 遍历vs1的行（结果行索引）
        row_result = []
        for j in range(8):  # 遍历vs2转置后的行（结果列索引）
            row1 = mat1[i]
            row2 = mat2[j]
            
            products = [row1[k] * row2[k] for k in range(8)]
            sum_val = sum(products)
            
            print(f"  结果[{i}][{j}] = ", end="")
            print(" + ".join([f"{a}×{b}" for a, b in zip(row1, row2)]), end="")
            print(f" = {sum_val}")
            
            row_result.append(sum_val)
        result.append(row_result)
        print()  # 行之间空行
    return result

def add_matrix(mat1, mat2):
    """矩阵元素相加：result[i][j] = mat1[i][j] + mat2[i][j]"""
    result = []
    print("\n矩阵元素相加过程：")
    for i in range(8):
        row = []
        for j in range(8):
            sum_val = mat1[i][j] + mat2[i][j]
            print(f"  结果[{i}][{j}] = {mat1[i][j]} + {mat2[i][j]} = {sum_val}")
            row.append(sum_val)
        result.append(row)
    return result

def print_full_hex_array(hex_list, name):
    """完整打印16进制格式数组"""
    print(f"{name}（共{len(hex_list)}个元素，16进制表示）：")
    for i in range(0, len(hex_list), 8):  # 32bit数值每行显示8个更合适
        print(f"  {hex_list[i:i+8]}")
    print()

def print_full_dec_array(arr, name):
    """完整打印10进制格式数组"""
    print(f"{name}（共{len(arr)}个元素，10进制表示）：")
    for i in range(0, len(arr), 8):
        print(f"  {arr[i:i+8]}")
    print()

def print_full_groups(groups, name):
    """完整打印分组数组"""
    print(f"{name}（共{len(groups)}组，每组8个元素，10进制表示）：")
    for i, group in enumerate(groups):
        print(f"  第{i+1}组：{group}")
    print()

def main():
    # 输入字符串
    str1 = "0x00000000163e57550067009d5e040ba200000000497fdf1a00a3007e8095ad5300000000cb6afb5b000300207a0fbf83000000008686e85900fe004a33f1f3d4"
    str2 = "0x00000000b83cf7e00000000025ca2825000000007a6e7cc2000000001ab3661c000000005748d972000000000bc6dead00000000041300d7000000001f9d941e"
    # 第三个输入（32bit数值，256个字符）
    str3 = "0x00000000d49f6e30010001007b9fb19700000000c7007da60100010118224a8401000000e6d565330001000081b17b4e0000010054720064000402090008000000000000330cc97a0000970000a7068500000000177baf520000139900a9d58c000000000000e3c90000000037b17b7b0000cd0044000018ffffffff00f3b30000000000eb1c5532000000000fafa6fd00000000a8770d4800000000e81b130200000000e96733760000000022088f8d00000000ec481cca040702090508090000000000b454b9b200000000e0f9a6c1000000007f14f4b900000000409c7c06000000004eed60ab00000000e0e06b3100000000da6e3f9700000000552fb24b"
    
    # 处理vs1（8bit）
    dec_array1, hex_array1 = str_to_hex_array(str1)
    print_full_hex_array(hex_array1, "vs1转换后的原始数组（8bit）")
    print_full_dec_array(dec_array1, "vs1转换后的数值数组（8bit）")
    
    vs1_groups = split_into_groups(dec_array1)
    print_full_groups(vs1_groups, "vs1拆分后的分组（作为矩阵行）")
    
    # 处理vs2（8bit）
    dec_array2, hex_array2 = str_to_hex_array(str2)
    print_full_hex_array(hex_array2, "vs2转换后的原始数组（8bit）")
    print_full_dec_array(dec_array2, "vs2转换后的数值数组（8bit）")
    
    vs2_groups = split_into_groups(dec_array2)
    print_full_groups(vs2_groups, "vs2原始拆分后的分组")
    
    vs2_transposed = transpose_groups(vs2_groups)
    print_full_groups(vs2_transposed, "vs2转置后的分组（作为矩阵行）")
    
    # 处理第三个矩阵（32bit）
    dec_array3, hex_array3 = str_to_hex_array(str3, is_32bit=True)
    print_full_hex_array(hex_array3, "第三个矩阵转换后的原始数组（32bit）")
    print_full_dec_array(dec_array3, "第三个矩阵转换后的数值数组（32bit）")
    
    mat3_groups = split_into_groups(dec_array3)
    print_full_groups(mat3_groups, "第三个矩阵拆分后的分组（作为8x8矩阵）")
    
    # 构建8x8矩阵
    vs1_matrix = vs1_groups[:8] if len(vs1_groups)>=8 else vs1_groups + [[0]*8]*(8-len(vs1_groups))
    vs2_matrix = vs2_transposed[:8]
    mat3 = mat3_groups[:8] if len(mat3_groups)>=8 else mat3_groups + [[0]*8]*(8-len(mat3_groups))
    
    # 打印所有矩阵
    print("用于计算的8x8矩阵：")
    print("vs1矩阵（行）：")
    for i, row in enumerate(vs1_matrix):
        print(f"  第{i+1}行：{row}")
    print()
    print("vs2转置后矩阵（行）：")
    for j, row in enumerate(vs2_matrix):
        print(f"  第{j+1}行：{row}")
    print()
    print("第三个矩阵（行）：")
    for i, row in enumerate(mat3):
        print(f"  第{i+1}行：{row}")
    print()
    
    # 计算vs1与vs2转置的点乘结果
    dot_product_result = matrix_dot_product(vs1_matrix, vs2_matrix)
    
    # 打印点乘中间结果
    print("\nvs1与vs2转置的点乘结果（10进制）：")
    for i, row in enumerate(dot_product_result):
        print(f"  第{i+1}行：{row}")
    
    # 将点乘结果与第三个矩阵元素相加
    final_result = add_matrix(dot_product_result, mat3)
    
    # 输出最终结果
    print("\n最终结果（点乘结果 + 第三个矩阵，10进制）：")
    for i, row in enumerate(final_result):
        print(f"  第{i+1}行：{row}")

if __name__ == "__main__":
    main()

